package cn.codingjc.nacos;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;

import java.util.Properties;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;

/**
 * @author: Allen.qiu
 * @Date: 2022/7/16 17:04
 * @description:
 **/
public class NacosConfigListener {
    public static final String NACOS_SERVER = "192.168.239.131:8848";
    public static final String DATA_ID = "cn.codingjc.nacos.microcloud.config";
    public static final String GROUP = "MICROCLOUD_GROUP";
    public static final String NAMESPACE = "a3575eaf-f53a-481a-807a-9277fe43e87f";

    public static void main(String[] args) throws NacosException, InterruptedException {
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.SERVER_ADDR, NACOS_SERVER);
        properties.put(PropertyKeyConst.NAMESPACE, NAMESPACE);
        ConfigService configService = NacosFactory.createConfigService(properties);
        String config = configService.getConfig(DATA_ID, GROUP, 5000);
        System.err.println("【初始化配置】" + DATA_ID + "=" + config);

        // 一般来说是在服务启动的时候进行配置数据的读取，但是也需要提供有数据的更新
        configService.addListener(DATA_ID, GROUP, new Listener() {
            @Override
            public Executor getExecutor() {
                return null;
            }

            // 数据有更新后可以自动的接受更新
            @Override
            public void receiveConfigInfo(String configInfo) {
                System.err.println("【配置项更新】" + DATA_ID + "=" + configInfo);
            }
        });
        TimeUnit.MINUTES.sleep(Long.MAX_VALUE);
    }
}
 